package normal.哈希表;

import normal.链表.ListNode;

import java.util.Arrays;

/**
 * @author ZhuYi
 * @create 2025/2/20 19:49
 * <p>
 * 哈希算法
 */
public class HashAlgorithm {
    public static void main(String[] args) {
        int num = 3;
        int hashNum = Integer.hashCode(num);
        // 整数 3 的哈希值为 3

        boolean bol = true;
        int hashBol = Boolean.hashCode(bol);
        // 布尔量 true 的哈希值为 1231

        double dec = 3.14159;
        int hashDec = Double.hashCode(dec);
        // 小数 3.14159 的哈希值为 -1340954729

        String str = "Hello 算法";
        int hashStr = str.hashCode();
        // 字符串“Hello 算法”的哈希值为 -727081396

        Object[] arr = {12836, "小哈"};
        int hashTup = Arrays.hashCode(arr);
        // 数组 [12836, 小哈] 的哈希值为 1151158

        ListNode obj = new ListNode(0);
        int hashObj = obj.hashCode();
        // 节点对象 utils.ListNode@7dc5e7b4 的哈希值为 2110121908

    }

    /* 加法哈希 */
    int addHash(String key) {
        long hash = 0;
        final int MODULUS = 1000000007;
        for (char c : key.toCharArray()) {
            hash = (hash + (int) c) % MODULUS;
        }
        return (int) hash;
    }

    /* 乘法哈希 */
    int mulHash(String key) {
        long hash = 0;
        final int MODULUS = 1000000007;
        for (char c : key.toCharArray()) {
            hash = (31 * hash + (int) c) % MODULUS;
        }
        return (int) hash;
    }

    /* 异或哈希 */
    int xorHash(String key) {
        int hash = 0;
        final int MODULUS = 1000000007;
        for (char c : key.toCharArray()) {
            hash ^= (int) c;
        }
        return hash & MODULUS;
    }

    /* 旋转哈希 */
    int rotHash(String key) {
        long hash = 0;
        final int MODULUS = 1000000007;
        for (char c : key.toCharArray()) {
            hash = ((hash << 4) ^ (hash >> 28) ^ (int) c) % MODULUS;
        }
        return (int) hash;
    }
}

